package com.dsiab.manageService.common;

import com.dsiab.manageService.mapper.AccountDao;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class CommonUtils {
    @Autowired
    AccountDao accountDao;

    public String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("X-Real-IP");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("X-Forwarded-For");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("REMOTE-HOST");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress="";
        }
        return ipAddress;
    }
    public String getRoleListByString(String username) {
        // 动态获取权限, 通过逗号拼接角色Id
        List<Map> roleList = accountDao.getRolesByUserName(username);

        String roleListjoin = "";
        for (int i =0; i<roleList.size();i++){
            if (i != (roleList.size() -1)){
                roleListjoin += roleList.get(i).get("roleId") + ",";
            } else {
                roleListjoin += roleList.get(i).get("roleId");
            }
        }
        return roleListjoin;
    }
    public Boolean isImg(String fileName){
        return fileName.contains("jpg") || fileName.contains("jpeg") || fileName.contains("png");
    }
}
